package com.hs.pre.module.sort;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hs.pre.model.SortExcelBean;

import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelImport {

	/**
	 * 结果集
	 */
	 private List list = new ArrayList();
	 
	 private InputStream inputStream;
	 
	 public ExcelImport(InputStream inputStream)
	 {
		 this.inputStream = inputStream;
		 this.initData();
	 }
	 
	 /**
	  * 解析Excel文件
	  */
	 private void initData()
	 {
		 if(inputStream == null)
			 return;
		 try {
			jxl.Workbook rwb= Workbook.getWorkbook(inputStream);
			jxl.Sheet sh= rwb.getSheet(0);
			int rowCount= sh.getRows();
			for(int i=0; i < rowCount; i++)
			{
				jxl.Cell[] ce= sh.getRow(i);
				int cellSize = ce.length;
				String[] data = new String[cellSize];
				for(int y = 0; y < cellSize ; y++)
				{
					data[y] = ce[y].getContents().toString();
				}
				this.list.add(data);
			}
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	 }
	 
	 /**
	  * 原始数据
	  * @return
	  */
	 public List getData()
	 {
		 return list;
	 }
	 
	 
	 /**
	  * 处理后的成树形结构
	  * @param pId 上级节点id
	  * @return
	  */
	 public List getDealData(int pId)
	 {
		    List deal = new ArrayList();
			Iterator iterator = list.iterator();
			Map map = new HashMap();
			while(iterator.hasNext())
			{
				String[] tem = (String[])iterator.next();
				int size = tem.length;
				for(int i=0;i<size;i++)
				{
					 String temItem = tem[i];
					 if(!temItem.equals(""))
					 {
						 SortExcelBean sortExcelBean = new SortExcelBean();
						 sortExcelBean.setSortName(temItem);
						 SortExcelBean sortExcelBeanTem = (SortExcelBean)map.get(new Integer(i-1));
						 if(sortExcelBeanTem == null)
						 {
							 sortExcelBean.setParentSortId(pId);
							 deal.add(sortExcelBean);
						 }else{
							 sortExcelBeanTem.getChildList().add(sortExcelBean);
						 }
						 map.put(new Integer(i), sortExcelBean);
						 break;
					 }
				}
			}
	   return deal;
	 }
}
